//
//  MySetVC.swift
//  YueChat
//
//  Created by IMac on 2024/9/14.
//

import UIKit

class MySetVC: BaseVC, UIImagePickerControllerDelegate & UINavigationControllerDelegate {
    
    var userInfo = DMCCUser()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "我的个人信息"
        setup()
        self.getUserInfo()
    }


    func setup () {
//        dataSource = ["头像","昵称","我的二维码"]
        tableView.register(UINib(nibName: "SubTitleCell", bundle: nil), forCellReuseIdentifier: "SubTitleCell")
        tableView.register(UINib(nibName: "RightImgCell", bundle: nil), forCellReuseIdentifier: "RightImgCell")
        self.tableView.reloadData()
    }
    
    func getUserInfo () {
        if let user = gosnUser.getUserInfo(""){
            self.userInfo = user
            GK_main_async_safe {
                self.tableView.reloadData()
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0   {
            return 100
        }
        return 60
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        return 2
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//        if section == 1 {
//            return 1.000
//        }
       return 0.001
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "RightImgCell", for: indexPath) as! RightImgCell
            cell.nameLab.text = "头像"
            cell.img.sd_setImage(with: URL(string: self.userInfo.portrait), placeholderImage: SDImageDefault)
            cell.imgWidth.constant = 60
            cell.imgHeight.constant = 60
            return cell
        }
        
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SubTitleCell", for: indexPath) as! SubTitleCell
            cell.titleLab.text = "昵称"
            cell.subTitleLab.font = UIFont.systemFont(ofSize: 16)
            cell.subTitleLab.textColor = UIColor.black
            cell.subTitleLab.text = self.userInfo.getAlias()
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "RightImgCell", for: indexPath) as! RightImgCell
        cell.nameLab.text = "我的二维码"
        cell.imgWidth.constant = 32
        cell.imgHeight.constant = 32
        cell.img.image = UIImage(named: "qr_hui")
        return cell
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
        
        if indexPath.section == 0 {
            self.getHeadImg()
        }
        if indexPath.row == 0 {
            
            let vc = SetNickNameVC(type: .my, SId: self.userInfo.userId) {
                self.getUserInfo()
            }
            self.presentVC(VC: vc)

            
        }else if indexPath.row == 1 {
            self.navigationController?.pushViewController(QRVC(with: DMCCConversation(), isGroup: false, isUser: false), animated: true)
        }
    }
    
    lazy var imagePickerVc: UIImagePickerController = {
        let pickerVc = UIImagePickerController()
        pickerVc.delegate = self
        pickerVc.navigationBar.barTintColor = self.navigationController?.navigationBar.barTintColor
        pickerVc.navigationBar.tintColor = self.navigationController?.navigationBar.tintColor
        let tzBarItem = UIBarButtonItem.appearance(whenContainedInInstancesOf: [TZImagePickerController.self])
        let barItem = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UIImagePickerController.self])
        let titleTextAttributes = tzBarItem.titleTextAttributes(for: .normal)
        barItem.setTitleTextAttributes(titleTextAttributes, for: .normal)
        return pickerVc
    }()
    
    func getHeadImg () {
        let tzImagePickerVC = TZImagePickerController(maxImagesCount: 1, columnNumber: 1, delegate: nil, pushPhotoPickerVc: true)
        tzImagePickerVC?.allowCrop = true
        
//        tzImagePickerVC?.allowTakeVideo = false
//        tzImagePickerVC?.allowTakePicture = false
//        tzImagePickerVC?.allowPickingVideo = false
        tzImagePickerVC?.modalPresentationStyle = .fullScreen
        tzImagePickerVC?.preferredLanguage = "zh-Hans"
//        tzImagePickerVC?.allowPreview = true
        self.present(tzImagePickerVC!, animated: true)
      ///从相册中选取图片完成后的回调
        tzImagePickerVC!.didFinishPickingPhotosHandle = { photos,assets,isSelectOriginalPhoto in
            if let img = photos?.first {
                self.uploadHeadImage(img: img)
            }
        }
    }
    
    func uploadHeadImage (img:UIImage) {
        let data = img.jpegData(compressionQuality: 1)! as Data
        
        SVProgressHUD.show()
        
        Task {
            let (url,error) = await ghttpService.uploadUserPortrait(data)
            
            let res =  await gosnUser.setPortraitWithUrl(url!)
            
            await MainActor.run {
                SVProgressHUD.dismiss()
                
                if res {
                    self.DelectNFT()
                    
                    MHAlert.showMessage(KLocalizedString("AlertLoadSuccess"))
                    self.getUserInfo()
                }else{
                    MHAlert.showMessage(KLocalizedString("AlertSettingFail"))
                }
            }
        }
        
//        _ = FileTool.shared.uploadPortrait(mediaData: data as Data) {[weak self] url in
//             guard let self = self else {return}
//             Task{
//                 let res =  await gosnUser.setPortraitWithUrl(url)
//                         
//                 await MainActor.run {
//                     SVProgressHUD.dismiss()
//                     if res {
//                         self.DelectNFT()
//                         
//                         MHAlert.showMessage(KLocalizedString("AlertLoadSuccess"))
//                         self.getUserInfo()
//                     }else{
//                         MHAlert.showMessage(KLocalizedString("AlertSettingFail"))
//                     }
//                 }
//             }
//        } progress: { upload, total in
//            print("[FW]:\(upload) - \(total)")
//        } error: { error in
//            SVProgressHUD.dismiss()
//            GK_main_async_safe {
//                MHAlert.showMessage(KLocalizedString("AlertSettingFail"))
//            }
//        }


    }
    
    func DelectNFT () {
        Task {
            _ = await gosnUser.setNft("")
            _ = await gosnUser.fetchMyInfo()

        }
        
//        DMCCIMService.getInstance().sendRemoveNFTDescribesWithcb { Success, json, error in
//            if Success == true {
//                self.getUserInfo()
//            }
//        }
    }
    
//    func changeName() {
//        let alertController = UIAlertController(title: "", message: "修改昵称", preferredStyle: .alert)
//
//        // 添加一个文本字段
//        alertController.addTextField { (textField) in
//            textField.placeholder = "Please enter a name"
//        }
//
//        // 添加取消按钮
//        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in
//            
//            self.dismiss(animated: true)
//        }
//        alertController.addAction(cancelAction)
//
//        // 添加确定按钮
//        let okAction = UIAlertAction(title: "Done", style: .default) { (_) in
//            if let textfield = alertController.textFields?.first {
//                
//                let text = textfield.text
////                self.setName(name: text!)
//            }
//        }
//        alertController.addAction(okAction)
//
//        // 显示弹窗
//        self.present(alertController, animated: true, completion: nil)
//    }

//    func setName (name:String) {
//        if name.count > 12 {
//            MHAlert.showMessage("不能超过12个字")
//            return
//        }
//
//        if let dic = UserDefaults.standard.object(forKey: MHHYCrossImSensitiveWords) as? [String: Any],
//           let sensitiveWordsArr = dic["keywordArray"] as? [String] {
//            for component in sensitiveWordsArr {
//                if name.contains(component) == true {
//                    switch type {
//                    case .my:
//                        MHAlert.showError("昵称违规，请重新输入")
//                    case .user:
//                        MHAlert.showError("昵称违规，请重新输入")
//                    case .group:
//                        MHAlert.showError("群组昵称违规，请重新输入")
//                    default:
//                        MHAlert.showError("群昵称违规，请重新输入")
//                    }
//                    return
//                }
//            }
//        }
//    }
    
}



